package org.springcloud.wisdom.spring_02_classroom.student.choose.service;

import org.springcloud.wisdom.spring_02_classroom.admin.createcourse.entity.Course;
import org.springcloud.wisdom.spring_02_classroom.bean.Page;
import org.springcloud.wisdom.spring_02_classroom.student.choose.dao.ChooseCourseDao;
import org.springcloud.wisdom.spring_02_classroom.student.choose.entity.ChooseCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChooseCourseService {
    @Autowired
    ChooseCourseDao chooseCourseDao;

    //查看所有课程信息
    public Page<Course> AllCourse(int pageNum, int pageSize){
        //计算起始位置
        int start=(pageNum-1)*pageSize;
        //获取分页的数据
        List<Course> list= chooseCourseDao.get(start,pageSize);
        //获取总条目数
        int total= chooseCourseDao.CountCourses();
        //计算总页数
        int pages =(int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
        //创建分页对象
        Page<Course> page=new Page<>();
        page.setRecords(list);
        page.setTotal(total);
        page.setPages(pages);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return page;
    }

    //选课
    public boolean insert(ChooseCourse chooseCourse) {
        if (chooseCourse == null) {
            return false;
        }
        // 检查课程号、学号和教师编号是否为空
        if (chooseCourse.getCid() == null || chooseCourse.getCid().trim().length() == 0 ||
                chooseCourse.getSid() == null || chooseCourse.getSid().trim().length() == 0 ||
                chooseCourse.getTid() == null || chooseCourse.getTid().trim().length() == 0) {
            return false;
        }

        // 查询数据库，检查是否已经选了同一时间的课程
        boolean isExistSameTimeCourse = chooseCourseDao.isExistSameTimeCourse(chooseCourse.getSid(), chooseCourse.getLtime());
        if(isExistSameTimeCourse){
            return false;
        }
        // 查询数据库，检查是否已经选过这门课程
        boolean isAlreadyChosen = chooseCourseDao.isAlreadyChosen(chooseCourse.getSid(), chooseCourse.getCid());
        if (isAlreadyChosen) {
            // 如果已经选过，返回错误信息
            return false;
        }

        // 插入选课记录
        boolean result = chooseCourseDao.insert(chooseCourse) > 0;
        return result;
    }
}
